const Timestamp = new Date().getTime() // 当前时间为了防止打包缓存不刷新，所以给每个js文件都加一个时间戳
const entryConfig = require('./pagesSetting') // 生成入口文件对象
const CDNConfig = require('./assetsCDN') // cdn配置项
const webpack = require('webpack')
const createThemeColorReplacerPlugin = require('./src/common/components/ThemeReplacer/plugin.config.js')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const buildDate = JSON.stringify(new Date().toLocaleString())
const isProd = process.env.NODE_ENV === 'production'
var projectname = process.argv[3]

// const projectnameArr = process.argv.slice(3)
// 默认CDNJS
let JS = [
  'js/vue.min.js',
  'js/vue-router.min.js',
  'js/vuex.min.js',
  'js/axios.min.js'
]
const assetsCDN = {
  externals: {
    vue: 'Vue',
    'vue-router': 'VueRouter',
    vuex: 'Vuex',
    axios: 'axios'
  },
  singleEntry: {
    js: []
  }
}
const cnds = CDNConfig.CDN() || {}
const pages = entryConfig.discriminate()
if (!projectname) {
  setCDN(Object.keys(pages), cnds)
}
console.log('当前入口页面--------------------')
console.log(pages)
console.log('-----------开始！！！')
const vueConfig = {
  configureWebpack: config => {
    config.externals = isProd ? assetsCDN.externals : {}
    config.output.filename = `js/[name].${Timestamp}.js`
    config.output.chunkFilename = `js/[name].${Timestamp}.js`
    // 动态修改主题色
    config.plugins.push(createThemeColorReplacerPlugin())
    if (isProd) {
      // 开启gzip压缩
      const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i
      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: productionGzipExtensions,
          threshold: 10240,
          minRatio: 0.8
        })
      )
      config.performance = {
        hints: 'warning',
        // 入口起点的最大体积
        maxEntrypointSize: 10000000,
        // 生成文件的最大体积
        maxAssetSize: 30000000,
        // js 文件的性能提示
        assetFilter: function (assetFilename) {
          return assetFilename.endsWith('.js')
        }
      }
      // 开启分离js
      config.optimization = {
        splitChunks: {
          chunks: 'all',
          cacheGroups: {
            // 新增分离antd
            antd: {
              name: 'chunk-antd',
              priority: 20,
              test: /[\\/]node_modules[\\/]_?ant-design-vue(.*)/
            },
            vendors: {
              name: 'chunk-vendors',
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
              chunks: 'initial'
            },
            common: {
              name: 'chunk-common',
              minChunks: 2,
              priority: 5,
              chunks: 'initial',
              reuseExistingChunk: true
            }
          }
        }
      }
    } else {
      config.plugins.push(
        new webpack.DefinePlugin({
          APP_VERSION: `"${require('./package.json').version}"`,
          BUILD_DATE: buildDate
        })
      )
    }
  },
  chainWebpack: config => {
    let pagesArr = []
    // 移除 prefetch preload 插件
    for (let key in pages) {
      config.plugins.delete('prefetch-' + key + '')
      config.plugins.delete('preload-' + key + '')
      pagesArr.push(key)
    }
    setCDN(pagesArr, cnds)
    for (let k in pages) {
      config.plugin('html-' + k).tap(args => {
        isProd ? (args[0].cdn = assetsCDN[k]) : void 0
        args[0].CONFIG = k
        return args
      })
    }
  },
  css: {
    sourceMap: !isProd,
    loaderOptions: {
      less: {
        modifyVars: {},
        javascriptEnabled: true
      }
    }
  },
  pages: pages,
  runtimeCompiler: !isProd,
  productionSourceMap: !isProd,
  publicPath: projectname ? '/' + projectname : '',
  outputDir: projectname ? 'dist/' + projectname : 'dist',
  devServer: {
    compress: true,
    proxy: {
      [process.env.VUE_APP_API]: {
        // target: 'http://10.40.231.104:8889', // 测试服务器
        target: 'http://10.40.204.34:9989', // 测试服务器
        // target: 'http://10.40.204.34:8889', // 测试服务器
        pathRewrite: {
          '^/api': ''
        },
        changeOrigin: true
        // logLevel: 'debug'
      }
    }
  }
}
function setCDN (pages, cdn) {
  // 合并externals和CDN
  pages.forEach(i => {
    for (let keys in cdn) {
      if (i === keys) {
        assetsCDN.externals = { ...cdn[i].externals, ...assetsCDN.externals }
        assetsCDN[i].js = [...JS, ...cdn[i].js]
        assetsCDN[i].css = [...cdn[i].css]
      }
    }
  })
}

module.exports = vueConfig
